import React, { Component } from 'react';
import './form.less';
import BreadcrumbCustom from '../common/BreadcrumbCustom';
import CollectionCreateForm from './CustomizedForm';
import FormTable from './FormTable';
import { message, Modal, Button } from 'antd';
import fetchRequest from '../../fetch/fetchRequest';
import moment from 'moment';

// 找到对应元素的索引
function catchIndex(arr, id) { // 获取INDEX
    let index = 0;
    arr.forEach(function (ar, ind) {
        if (ar.id === id) {
            index = ind;
        }
    });
    return index;
}

export default class Order extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userName: '',
            timeRange: '',
            visible: false, // 新建窗口隐藏
            dataSource: [],
            isUpdate: false,
            loading: true,
            formData: { username: '', orderPrincipal: '', orderCommission: '', orderRemarks: '' },
            selectedRowKeys: [],
            settlement: false
        };
    }
    // 获取订单列表
    getUsersList() {
        const body = { username: JSON.parse(localStorage.getItem("mspa_user")).username }
        fetchRequest.fetchR('orders/username', 'POST', body)
            .then((response) => {
                response.sort(function (a, b) {
                    return Date.parse(b.orderTime) - Date.parse(a.orderTime);//时间降序
                });

                // 展示最近三天的数据
                // const today = moment().format("YYYY/MM/DD");
                // let currenDay = today;
                // for (let i = 0; i < 3; i++) {
                //     let index = 0;
                //     response.map((item => {
                //         let orderTime = item.orderTime.split(' ')[0];
                //         if (orderTime === currenDay) {
                //             item.index = index + 1;
                //             index++;
                //         }
                //     }))
                //     currenDay = new Date(Date.parse(currenDay) - 1000 * 60 * 60 * 24).format("yyyy/MM/dd");
                // }
                // const threeData = response.filter(item => item.index !== undefined)

                // 展示全部订单
                response.forEach((item, index) => {
                    item.index = index + 1
                })

                this.setState({
                    // dataSource: threeData, // 最近三天的数据
                    dataSource: response, // 所以订单的数据
                    loading: false
                })
            }).catch((err) => {  //网络请求失败返回的数据
                message.error('数据获取失败')
            });
    }

    // 渲染
    componentDidMount() {
        this.getUsersList();
    }
    //接受新建表单数据
    saveFormRef = (form) => {
        this.form = form;
    };
    // 取消
    handleCancel = () => {
        this.setState({ visible: false });
    };
    // 点击修改
    editClick = (key) => {
        const { dataSource } = this.state;
        const index = catchIndex(dataSource, key);
        this.setState({
            visible: true,
            tableRowKey: key,
            formData: dataSource[index]
        });
    };
    // 更新修改
    handleUpdate = () => {
        const form = this.form;
        const { dataSource, tableRowKey } = this.state;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }

            // 除备注，其他项不变
            const index = catchIndex(dataSource, tableRowKey);
            values.orderTime = dataSource[index].orderTime;
            values.orderNumber = dataSource[index].orderNumber;
            values.username = dataSource[index].username;
            values.orderPrincipal = dataSource[index].orderPrincipal;
            values.orderCommission = dataSource[index].orderCommission;
            values.operator = dataSource[index].operator;

            fetchRequest.fetchR(`orders/${tableRowKey}`, 'put', values)
                .then(respones => {
                    message.success('备注成功！')
                    this.getUsersList();
                    this.setState({
                        visible: false
                    });
                    form.resetFields();
                }).catch(err => {
                    message.error('备注失败!');
                    this.setState({
                        visible: false
                    });
                    form.resetFields();
                })

            values.id = tableRowKey;
        });
    };

    // 选择的订单
    selectedOrders = (selectedRowKeys) => {
        this.setState({ selectedRowKeys });
        if (selectedRowKeys.length === 0) {
            this.setState({
                settlement: false
            })
        }
    }
    // 选中订单结算
    settlement = () => {
        const { selectedRowKeys, dataSource } = this.state;
        if (selectedRowKeys.length === 0) {
            Modal.info({ content: '请选择至少一个订单', okText: '确定' })
        } else {
            let benjin = 0;
            let yongjin = 0;
            dataSource.forEach(item => {
                if (selectedRowKeys.indexOf(item.id) > -1) {
                    benjin += item.orderPrincipal;
                    yongjin += item.orderCommission;
                }
            })
            this.setState({
                benjinSettlement: benjin,
                yongjinSettlement: yongjin,
                settlement: true
            })
        }
    }
    // 清空选择
    start = () => {
        this.setState({
            selectedRowKeys: [],
            settlement: false
        });
    }

    render() {
        const { dataSource, visible, loading, formData, selectedRowKeys, benjinSettlement, yongjinSettlement, settlement } = this.state;
        const today = moment().format("YYYY/MM/DD");
        let count = 0;
        let benjin = 0;
        let yongjin = 0;
        dataSource.forEach(item => {
            let orderTime = item.orderTime.split(' ')[0];
            if (orderTime === today) {
                count = count + 1;
                benjin += item.orderPrincipal;
                yongjin += item.orderCommission;
            }
        })

        // 选中的订单数
        const hasSelected = selectedRowKeys.length > 0;
        return (
            <div>
                <BreadcrumbCustom paths={['订单管理']} />
                <div className='formBody'>
                    <Button
                        type="primary"
                        onClick={this.start}
                        disabled={!hasSelected}
                    >
                        清空选择
                    </Button>
                    <Button onClick={this.settlement} style={{ marginLeft: 8 }}>结算</Button>
                    <span style={{ marginLeft: 8 }}>
                        {hasSelected ? <span>已选 <span style={{ fontWeight: 'bold' }}>{selectedRowKeys.length} </span>项；</span> : ''}
                        {settlement ? <span>所选订单本金共：<span style={{ fontWeight: 'bold' }}>{parseFloat(benjinSettlement).toFixed(2)}</span>元；
                        佣金共：<span style={{ fontWeight: 'bold' }}>{parseFloat(yongjinSettlement).toFixed(2)}</span>元</span> : ''}
                    </span>
                    <span style={{ float: 'right' }}>
                        今日订单共：<span style={{ fontWeight: 'bold' }}>{count}</span>单；
                        本金：<span style={{ fontWeight: 'bold' }}>{parseFloat(benjin).toFixed(2)}</span>元；
                        佣金：<span style={{ fontWeight: 'bold' }}>{parseFloat(yongjin).toFixed(2)}</span>元
                    </span>
                    <FormTable
                        dataSource={dataSource}
                        editClick={this.editClick}
                        loading={loading}
                        selectedOrders={this.selectedOrders}
                        selectedRowKeys={selectedRowKeys}
                    />
                    <CollectionCreateForm
                        ref={this.saveFormRef}
                        visible={visible}
                        formData={formData}
                        onCancel={this.handleCancel}
                        onCreate={this.handleUpdate}
                        title="修改信息"
                        okText="更新" />
                    {/* <span style={{ color: 'orange' }}>注：只展示最近三天的数据！若最近三天无数据则不展示</span> */}
                </div>
            </div>
        )
    }
}